package com.Offer;

import com.pojo.ListNode;

/*
    面试题22：链表中倒数第K个节点
    输入一个链表，输出该链表中倒数第 k 个结点。
    测试用例：1,2,3,4,5,6
    特殊用例：k=0,k=11
 */
public class demo22 {
    public static void main(String[] args) {

        int[] input = new int[]{1,2,3,4,5,6};
        ListNode head = new ListNode(1);
        for(int i = 1;i<input.length;i++){
            head.add(input[i]);
        }

        ListNode kthToTail = findKthToTail(head, 2);
        if(kthToTail == null){
            System.out.println("null");
        }else{
            System.out.println(kthToTail.val);
        }

    }

    public static ListNode findKthToTail(ListNode head,int k) {
        if (head == null || k < 1)
            return null;
        ListNode fast = head;
        ListNode slow = head;

        while (k-- > 1) {
            if (fast.next == null) {
                return null;
            }
            fast = fast.next;
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}
